<template>
  <section class="todoapp">
    <!-- 头部部分 -->
   <TodoHeader @addList="addList"/>

    <!-- 主体部分 -->
   <TodoBody :list="renderList" @delList="delList" @changeIsdone="changeIsdone" :isCheakAll="isCheakAll" @changeCheak="changeCheak" />

    <!-- 底部部分 -->
   <TodoFooter :lonelyList="lonelyList" @removeAll="removeAll" v-show="list.length" :isDoneAll="isDoneAll" :type="type" @changeType="changeType" />
  </section>
</template>

<script>

import TodoHeader from '@/components/TodoHeader.vue'
import TodoBody from '@/components/TodoBody.vue'
import TodoFooter from '@/components/TodoFooter.vue'
export default {
  components:{
    TodoHeader,TodoBody,TodoFooter
  },
  data(){
    return{
    list: JSON.parse(localStorage.getItem('ToDoList'))||[],
    type:'all',
    // newList:''
    }
  },
  methods:{
    //删除事件
  delList(id){
this.list=this.list.filter(item=>item.id!==id)
  },
  //修改事件
  changeIsdone(id){
    const obj=this.list.find(item=>item.id===id)
    obj.isDone=!obj.isDone
  },
  addList(text){
  const obj={id:+new Date(),name:text,isDone:false}
  this.list=[obj,...this.list]
  },
  removeAll(){
  this.list=this.list.filter(item=>!item.isDone)
  },
  changeType(type){
    this.type=type
  },
  changeCheak(flag){
    this.list.forEach(item =>item.isDone=flag);
  }
  },
  computed:{
    lonelyList(){
      return this.list.filter(item=>!item.isDone).length
    },
    isDoneAll(){
      return this.list.some(item=>item.isDone)
    },
    renderList(){
      switch (this.type) {
        case 'all':
          return this.list

        case 'active':
          return this.list.filter(item=>!item.isDone)

        case 'completed':
          return this.list.filter(item=>item.isDone)

        default:
          return this.list

      }
    },
    isCheakAll(){
    return this.list.every(item=>item.isDone)
    }
  },
  watch:{
    list:{
      deep:true,
      handler(value){
      localStorage.setItem('ToDoList',JSON.stringify(value))
      }
    }
  }
}
</script>

<style></style>
